package com.dsx.haha.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dsx.haha.model.entity.User;
import com.dsx.haha.service.UserService;
import com.dsx.haha.utils.RedPrint;
import net.bytebuddy.implementation.bytecode.Throw;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.List;
import java.util.Map;

/**
 * @author dsx
 * @date 2021/3/8 17:09
 * @since JDK1.8
 */

public class UserRealm extends AuthorizingRealm {
    @Reference
    UserService userService;
    
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //一旦认证成功后，每次执行方法都会调用授权，,,认证和退出除外
        System.out.println("执行了==111111授权==doGetAuthorizationInfo");
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        Subject subject = SecurityUtils.getSubject();
        User dbuser = (User)subject.getPrincipal();
        List<String> userRoles = userService.getUserRoles(dbuser.getId());
        for (String userRole : userRoles) {
            RedPrint.print(userRole);
            simpleAuthorizationInfo.addRole(userRole);
        }
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了==22222认证==doGetAuthenticationInfo");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        User dbuser = userService.getUser(token.getUsername());
        if (dbuser==null){
            return null;
        }
        if (!(new String(token.getPassword())).equals(dbuser.getUserPwd())){
            throw new IncorrectCredentialsException();
        }
        SecurityUtils.getSubject().getSession().setAttribute("userLogin",token);
        SecurityUtils.getSubject().getSession().setAttribute("dbuser",dbuser);
        return new SimpleAuthenticationInfo(dbuser, dbuser.getUserPwd(),"");
    }
}